import time

from zz import zz_code, zz_dingtalk, zz_return, zz_log, zz_str
import requests

log = zz_log.of()


def run():
    token = zz_code.env("IKUUU_TOKEN")
    log.info(token)
    if zz_str.is_null_or_empty(token):
        log.error('未配置IKUUU_TOKEN')
        return

    log_msg = '**ikuuu签到** \n\n'
    handle = Handle(token)
    log_msg_one = handle.run_one()
    log.info(log_msg_one)
    log_msg += log_msg_one + "\n\n"

    zz_dingtalk.send_markdown(log_msg, "ikuuu签到")


# 民政工作日报
class Handle:
    def __init__(self, token):
        self.token = token

    def run_one(self):
        if zz_str.is_null_or_empty(self.token):
            return "缺少参数"
        log_msg = ''
        r_qian = self.api_qian()
        log_msg += f"{r_qian.get_errmsg()}"

        return log_msg

    def get_headers(self):
        headers = {
            "Cookie": f"{self.token}"
        }
        user_agent = zz_code.env("USER_AGENT")
        if zz_str.has_any_text(user_agent):
            headers['User-Agent'] = user_agent

        return headers

    # 签到
    def api_qian(self):
        api_url = f"https://ikuuu.one/user/checkin"
        headers = self.get_headers()
        post_data = {
        }

        log.debug(api_url)
        log.debug(headers)
        log.debug(post_data)
        res = requests.post(api_url, data=post_data, headers=headers)
        r = self.to_return(res.content)
        return r

    def to_return(self, content) -> zz_return.Return:
        log.debug(content)
        try:
            r = zz_return.parse(content)
            errcode = r.get_data('ret')
            errmsg = r.get_data('msg')
            r.set_errmsg(errmsg)
            r.set_errcode(errcode)
        except Exception as ex:
            log.error(ex)
            r = zz_return.of(123456, ex)
        log.info(f"return: {r.to_json()}")

        return r


if __name__ == '__main__':
    run()
